package com.heaven.jane.sourcegenerator.commons.security.authority.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.SetJoin;

import org.springframework.data.jpa.domain.Specification;

import com.heaven.jane.sourcegenerator.commons.security.authority.domain.Authority;
import com.heaven.jane.sourcegenerator.commons.security.user.domain.User;

import lombok.Builder;
import lombok.Data;

@Builder
@Data
public class AuthoritySpec implements Specification<Authority> {
	
	private static final long serialVersionUID = 1L;
	
	/**
	 * 条件
	 */
	@Builder.Default
	private Optional<Authority> authorityCondition = Optional.empty();
	
	/**
	 * 条件
	 */
	@Builder.Default
	private Optional<User> userCondition = Optional.empty();

	@Override
	public Predicate toPredicate(Root<Authority> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
		List<Predicate> predicates = new ArrayList<Predicate>();
		if(authorityCondition.isPresent()) {
			
		}
		
		if(userCondition.isPresent()) {
			if(userCondition.get().getId() != null) {
				SetJoin<Authority, User> users = root.join(root.getModel().getSet("users", User.class), JoinType.LEFT);
				predicates.add(users.in(userCondition.get().getId()));
			}
		}
		
		if(predicates.isEmpty()) {
			return null;
		}else {
			return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
		}
	}

}
